﻿using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Net.Sockets;

public class ScoketClient : MonoBehaviour
{
    const int Port = 8080;//端口号与服务端端口对应
    private TcpClient client;
    byte[] data;
    public string UserName = "";//用户名
    public string message = "";//聊天内容
    public string sendMsg = "";//输入框
    void OnGUI()
    {
        UserName = GUI.TextField(new Rect(890, 865, 120, 20), UserName);
        message = GUI.TextArea(new Rect(800, 890, 300, 100), message);
        sendMsg = GUI.TextField(new Rect(800, 1000, 210, 20), sendMsg);
        if (GUI.Button(new Rect(1020, 865, 80, 20), "连接服务器"))
        {
            this.client = new TcpClient();
            this.client.Connect("49.233.108.158", Port);
            data = new byte[this.client.ReceiveBufferSize];
            SendSocket(UserName);
            this.client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this.client.ReceiveBufferSize), ReceiveMessage, null);
        };
        if (GUI.Button(new Rect(1020, 1000, 80, 20), "发送"))
        {
            SendSocket(sendMsg);
            sendMsg = "";
        };
    }
    public void SendSocket(string message)
    {
        try
        {
            NetworkStream ns = this.client.GetStream();
            byte[] data = System.Text.Encoding.UTF8.GetBytes(message);
            ns.Write(data, 0, data.Length);
            ns.Flush();
        }
        catch (Exception ex)
        {
        }
    }
    public void ReceiveMessage(IAsyncResult ar)
    {
        try
        {
            int bytesRead;
            bytesRead = this.client.GetStream().EndRead(ar);
            if (bytesRead < 1)
            {
                return;
            }
            else
            {
                message += System.Text.Encoding.UTF8.GetString(data, 0, bytesRead);
            }
            this.client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this.client.ReceiveBufferSize), ReceiveMessage, null);
        }
        catch (Exception ex)
        {
        }
    }
}
